const router = require('koa-router')()
const { login } = require('../mysql/index.js')
const jwt = require('../utils/jwt.js')

router.post('/login', async (ctx, next) => {
  try {
    if(ctx.request.body.type === 'password'){//密码登录
      console.log(ctx.request.body);
      const res = await login({account: ctx.request.body.account})
      console.log(res);
      if(res.length === 0){
        ctx.body={
          code:'1',
          msg:'账号不存在'
        }
      }
      else{        
        if(res[0].password === ctx.request.body.value){
          let jwtToken = jwt.sign({number:res[0].phonenumber,name:res[0].name})
          ctx.body={
            code:'1',
            data:{
              name:res[0].name,
              number:res[0].phonenumber,
              token:jwtToken
            },
            msg:'登录成功'
          }
        }
        else{
          console.log('密码错误');
          ctx.body={
            code:'1',
            msg:'密码错误'
          }
        } 
      }
    }
    else{//验证码登录
      if(ctx.request.body.value.length === 6){
        if(res.length === 0){
          ctx.body={
            code:'1',
            msg:'账号不存在'
          }
        }
        else{
          let jwtToken = jwt.sign({number:res[0].phonenumber,name:res[0].name})
          ctx.body ={
            msg:'登录成功',
            code:'1',
            data:{
              name:res[0].name,
              number:res[0].phonenumber,
              token:jwtToken
            },
          } 
        }
      }
    }
  } catch (err) {
    console.log(err);
  }
})

module.exports = router